const accountTable = require('../models/accountTable');
const inspirecloud = require('@byteinspire/inspirecloud-api');
const mgRecordTable = require("../models/mgRecordTable");
const ObjectId = inspirecloud.db.ObjectId;


class AccountService {
    /**
     * 列出所有的记账记录
     */
    async listAll() {
        return await accountTable.where({is_delete: false}).sort({createAt: -1}).find();
    }

    /**
     * 列出分页内的账单记录
     */
    async queryById(params) {
        let {page, pageNum,info_id} = params;
        let queryParams = {is_delete: false};
        if (info_id !== undefined && info_id.trim() !== '') {
            queryParams.info_id = info_id;
        }
        let result = await accountTable.where(queryParams).count();
        let list = await accountTable.where(queryParams)
            .skip((page - 1) * pageNum)
            .limit(pageNum)
            .sort({createAt: -1}).find();
        let data = {note: list, total: result};
        return data;
    }

    /**
     * 根据id查找记录
     */
    async getOneById(id) {
        return await accountTable.where({_id: ObjectId(id)}).findOne();
    }


    /**
     * 创建一条账单事项
     * @param Account 用于创建账单事项的数据，原样存进数据库
     * @return {Promise<any>} 返回实际插入数据库的数据，会增加_id，createdAt和updatedAt字段
     */
    async create(Account) {
        return await accountTable.save(Account);
    }

    /**
     * 删除一条账单事项
     * @param id 账单事项的 _id
     * 若不存在，则抛出 404 错误
     */
    async delete(id) {
        const Account = await accountTable.where({_id: ObjectId(id)}).findOne();
        if (!Account) {
            const error = new Error(`account:${id} not found`);
            error.status = 404;
            throw error;
        }
        Account.is_delete = true;
        await accountTable.save(Account);
    }




    /**
     * 更新一条账单事项
     * @param newAccount._id 将会用原对象 merge 此对象进行更新
     * 若不存在，则抛出 404 错误
     */
    async update(newAccount) {
        const Account = await accountTable.where({_id: ObjectId(newAccount._id)}).findOne();
        if (!Account) {
            const error = new Error(`Account:${newAccount._id} not found`);
            error.status = 404;
            throw error;
        }
        Object.assign(Account, newAccount);
        Account._id = ObjectId(Account._id)
        await accountTable.save(Account);
    }


    async getGroupTypeIncomePrice(infoId) {
        let res = await accountTable
            .where({info_id: infoId, is_delete: false, manner: '收入'})
            .groupBy('type_name')
            .sum('money')
            .as('income_price')
            .find();
        return res;
    }

    async getGroupPaymentIncomePrice(infoId) {
        let res = await accountTable
            .where({info_id: infoId, is_delete: false, manner: '收入'})
            .groupBy('payment')
            .sum('money')
            .as('income_price')
            .find();
        return res;
    }

    async getGroupTypeExpenditurePrice(infoId) {
        let res = await accountTable
            .where({info_id: infoId, is_delete: false, manner: '支出'})
            .groupBy('type_name')
            .sum('money')
            .as('expenditure_price')
            .find();
        return res;
    }
    async getGroupPaymentExpenditurePrice(infoId) {
        let res = await accountTable
            .where({info_id: infoId, is_delete: false, manner: '支出'})
            .groupBy('payment')
            .sum('money')
            .as('expenditure_price')
            .find();
        return res;
    }

    async getUserPrice(infoId) {
        let res1 = await accountTable
            .where({info_id: infoId, is_delete: false, manner: '收入'})
            .groupBy('info_id')
            .sum('money')
            .as('income_price')
            .find();
        let res2 = await accountTable
            .where({info_id: infoId, is_delete: false, manner: '支出'})
            .groupBy('info_id')
            .sum('money')
            .as('expand_price')
            .find();
        let data = {income:res1,expand:res2};
        return data;
    }
}

// 导出 Service 的实例
module.exports = new AccountService();